function y = rs_encode(T,n,k,b)
% y = rs_encode(T,n,k,b)
%
% T is the message to be encoded, and it needs to be a Galois field 
% element. (Created by the gf() method of the Matlab Communication toolbox.) 
% n is the number of symbols in the encoded codeword
% k is the number of symbols in the information codeword
% b is defined by the formula in the BBC paper
% 
% Unlike the Matlab library function rsenc, this function can calculate the 
% RS codes for both odd and even values of (n-k), the number of redundant 
% symbols in the encoded codeword. 
% 
% The encoding is done as explained in the BBC White Paper.
% 
% This function uses the rs_init function in order the initialize the 
% lookup tables that are saved as global variables. 
%
% Tansu Demirbilek
% ademirbi@mc.com
% Mercury Computer Systems

% These values are calculated from the input variables. 
m = T.m;
N = 2^m-1; 
f = N-n;            % Code shortening factor
K = k+f;    % (N,K,m) for the original (unshortened) RS code
N_Tries = size(T,1);

% Calculate t depending on whether (n-k) is even or odd
if (mod(n-k,2)==0)
    t = (n-k)/2;
else
    t = (n-k-1)/2;
end

if(nargin ~= 4)
    b=0;
end
p = T.prim_poly;

gf_name = sprintf('GF_%d_%d_%d_%d_%d',N,K,m,b,p);
eval(sprintf('global %s',gf_name));

if(isempty( eval(gf_name)))
    rs_init(N,K,m,p,b);
end

% Create the local copies of the global variables
eval(sprintf('g = %s.g;',gf_name));
eval(sprintf('alpha_to = %s.alpha_to;',gf_name));
eval(sprintf('alpha_inv = %s.alpha_inv;',gf_name));
eval(sprintf('log_alpha = %s.log_alpha;',gf_name));

% Zero pad in the beginning for shortened values.
% Padding at the end is for redundancy check symbols
T = [zeros(N_Tries,f) T zeros(N_Tries,n-k)];
for j=1:N_Tries
    buffer = gf(zeros(1,(n-k+1)),m,p);
    list = zeros(2*K,(n-k+1));
    coeff = T(j,1);
    buffer = T(j,1:(n-k)+1);
    buffer = buffer + coeff * g;
    buffer = [buffer(2:end) 0];

    for i=1:K-1
        list(2*i-1,:) = buffer.x;
        buffer(end) = T(j,i+(n-k)+1);
        list(2*i,:) = buffer.x;
        coeff = buffer(1);
        buffer = buffer + coeff * g;
        buffer = [buffer(2:end) 0];
    end
    
    % Encoded Signal
    T(j,K+1:end) = buffer(1:end-1);
end
% Remove the padding if the code is a shortened RS code
y=T(:,f+1:end);

